package weeny.demo;

import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;

import prefuse.Constants;
import prefuse.action.ActionList;
import prefuse.action.RepaintAction;
import prefuse.action.layout.AxisLabelLayout;
import prefuse.controls.ControlAdapter;
import prefuse.data.query.NumberRangeModel;
import prefuse.render.AxisRenderer;
import prefuse.render.DefaultRendererFactory;
import prefuse.visual.expression.InGroupPredicate;
import weeny.pre.display.BaseUIDisplay;

public class AxisDemo {
	public static void shift(NumberRangeModel model, double frac){
		double range = (Double)model.getMaxValue()-(Double)model.getMinValue();
		double min = ((Double)model.getMinValue())+(range*frac);
		model.setMinValue(min); model.setLowValue(min);
		model.setMaxValue(min+range); model.setHighValue(min+range);
	}
	public static void main(String[] args) {
		final BaseUIDisplay display = new BaseUIDisplay();
		final Rectangle2D region = new Rectangle2D.Double(50, 50, 700, 500);
		final NumberRangeModel xRange = new NumberRangeModel(0d, 10, 0, 10);
		final NumberRangeModel yRange = new NumberRangeModel(0d, 10, 0, 10);
		AxisLabelLayout xLayout = new AxisLabelLayout("xlab", Constants.X_AXIS, xRange, region);
		AxisLabelLayout yLayout = new AxisLabelLayout("ylab", Constants.Y_AXIS, yRange, region);
		DefaultRendererFactory drf = ((DefaultRendererFactory)display.getVisualization().getRendererFactory());
		drf.add(new InGroupPredicate("xlab"), new AxisRenderer(Constants.CENTER, Constants.FAR_BOTTOM));
		drf.add(new InGroupPredicate("ylab"), new AxisRenderer(Constants.FAR_LEFT, Constants.CENTER));
		display.addControlListener(new ControlAdapter(){
			Point pressed = new Point(-1,-1);
			@Override
			public void mousePressed(MouseEvent e) {
				pressed.setLocation(e.getX(), e.getY());
				super.mousePressed(e);
			}
			@Override
			public void mouseDragged(MouseEvent e) {
				double dx = e.getX()-pressed.x;
				double dy = e.getY()-pressed.y;
				pressed.setLocation(e.getX(), e.getY());
				shift(xRange, 0-dx/region.getWidth());	
				shift(yRange, dy/region.getHeight());
				display.getVisualization().run("layout");
			}
		});
		ActionList actions = new ActionList();
		actions.add(xLayout);
		actions.add(yLayout);
		actions.add(new RepaintAction());
		display.getVisualization().putAction("layout", actions);
		display.getVisualization().run("layout");
		display.setSize(800, 600);
		display.showFrame("Axis Demo (Please drag)");
	}
}
